package leetcode;



//2982. 找出出现至少三次的最长特殊子字符串
public class Lc2982 {




    public int maximumLength(String s) {
        int[][] cnt = new int[26][3];
        int i = 0, j = 0;
        while (i <= j && j < s.length()) {
            if (s.charAt(i) == s.charAt(j)) {
                int len = j - i + 1;
                int index = s.charAt(i) - 'a';
                if (cnt[index][0] < len) {
                    cnt[index][2] = cnt[index][1];
                    cnt[index][1] = cnt[index][0];
                    cnt[index][0] = len;
                } else if (cnt[index][1] < len) {
                    cnt[index][2] = cnt[index][1];
                    cnt[index][1] = len;
                } else if (cnt[index][2] < len) {
                    cnt[index][2] = len;
                }
                j++;
            } else {
                i++;
            }
        }
        int ans = -1;
        for (int k = 0; k < 26; k++) {
            if (cnt[k][0] != 0 && cnt[k][0] == cnt[k][1] && cnt[k][1] == cnt[k][2]) {
                ans = Math.max(ans, cnt[k][0]);
            } else {
                if (cnt[k][1] == cnt[k][0]) {
                    ans = Math.max(ans, cnt[k][1] - 1);
                } else {
                    ans = Math.max(ans, cnt[k][2]);
                }
            }
        }
        return ans == 0 ? -1 : ans;
    }




}
